import React from "react";
import GoBack from "@/components/TheGoBack";
import { ManOutlined, WomanOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheDialog from "@/components/TheDialog";
import TheImage from "@/components/TheImage";
import TheButton from '@/components/TheButton';
import "../style/style.less";
import { Button, Pagination, Table, Typography } from "antd";
import DynamicDetails from "./DynamicDetails";
import { apiGetUserDetails, apiMemberDynamicPage, apiMemberBannedRecordPage, apiGetScorePage, apimemberDetailCouponPage, apiMemberIntegralRecord } from '@/request/users'
import { apiMemberBlockingAndUnblockingRecordQueryHistoryBanned } from '@/request/riskControl'
import _ from 'lodash'
import {maskNumber} from '@/utils/tools'

const { Text } = Typography;
class Details extends React.Component {
  state = {
    basicData: [],
    nickName: '',
    memberSex: '',
    couponColumns: [
      { title: "优惠券名称", dataIndex: "couponTitle", key: "couponTitle" },
      { title: "领取时间", dataIndex: "createTime", key: "createTime" },
      {
        title: "使用时间", dataIndex: "verificationTime", key: "verificationTime", render: (text, record) => {
          return (
            record.verificationTime == null ? '/' : record.verificationTime
          )
        }
      },
      { title: "过期时间", dataIndex: "endTime", key: "endTime" },
      {
        title: "优惠券状态", dataIndex: "status", key: "status", render: (text, record) => {
          return (
            record.status == null ? '/' : record.status
          )
        }
      },
    ],
    dynamicColumns: [
      { title: "发布时间", dataIndex: "createTime", key: "createTime" },
      { title: "内容摘要", dataIndex: "dynamicText", key: "dynamicText" },
      {
        title: "操作",
        render: (text, render) => {
          return (
            <Button type="link" onClick={() => this.openDialog(render.dynamicId)}>
              详情
            </Button>
          );
        },
      },
    ],
    bannedColumns: [
      {
        title: "封禁类型", dataIdnex: "bannedType", key: "bannedType", render: (text, render) => {
          let label = ''
          switch (render.bannedType) {
            case 'F':
              label = "冻结用户"
              break
            case 'B':
              label = "封禁发布"
              break
            default:
              label = '字段值有误'
          }
          return label;
        }
      },
      { title: "封禁原因", dataIndex: "bannedReason", key: "bannedReason" },
      { title: "封禁时间", dataIndex: "createTime", key: "createTime" },
      { title: "解封时间", dataIndex: "deadline", key: "deadline" },
    ],
    riskBannedColumns: [
      {
        title: "ID",
        dataIndex: "recordId",
        key: "recordId",
      },
      {
        title: "类型",
        dataIndex: "bannedTypeText",
        key: "bannedTypeText",
      },
      {
        title: "处理意见",
        dataIndex: "handlingOpinions",
        key: "handlingOpinions",
        render: (text, record) => {
          return <Text
            style={{ width: 300 }}
            ellipsis={{
              tooltip: text,
            }}
          >
            {text}
          </Text>
        }
      },
      {
        title: "封禁时间",
        dataIndex: "bannedTime",
        key: "bannedTime",
      },
      {
        title: "解封时间",
        dataIndex: "unsealTime",
        key: "unsealTime",
      },
      {
        title: "操作",
        fixed: "right",
        width: 200,
        render: (text, render) => {
          return (
            render.reportingRecordsId !== 'null' && <div>
              <TheButton onClick={() => this.goView(render.reportingRecordsId)}>查看</TheButton>
            </div>
          );
        },
      },
    ],
    couponData: [],
    dynamicData: [],
    bannedData: [],
    riskBannedData: [],
    couponPageNo: 1,
    dynamicPageNo: 1,
    bannedPageNo: 1,
    riskBannedPageNo: 1,
    couponTotal: 0,
    dynamicTotal: 0,
    bannedTotal: 0,
    riskBannedTotal: 0,
    visible: false,
    dynamicId: '',
    scorePageNo: 1,
    scoreColumns: [
      {
        title: '原因',
        dataIndex: 'recordTxt',
        key: 'recordTxt'
      },
      {
        title: '积分',
        render: (text, record) => {
          return <span style={{ color: record.recordType === '+' ? 'red' : 'green' }}>
            {`${record.recordType} ${_.toNumber(record.scoreNumber).toLocaleString()}`}
          </span>
        }
      },
      {
        title: '时间',
        dataIndex: 'createTime',
        key: 'createTime'
      }
    ],
    scoreDataSource: [],
    scoreTotal: 0,
    HaHaDouColumns: [
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        render: (text, record) => {
          if (record.integralNum >= 0) {
            return text = "收入"
          } else {
            return text = "支出"
          }
        }
      },
      {
        title: '条目类型',
        dataIndex: 'entryTypeName',
        key: 'entryTypeName'
      },
      {
        title: '哈哈豆',
        dataIndex: 'integralNum',
        key: 'integralNum',
        render: (text, record) => {
          if (text >= 0) {
            return text = "+" + text
          } else {
            return text
          }
        }
      },
      {
        title: '时间',
        dataIndex: 'createTime',
        key: 'createTime'
      }
    ],
    HaHaDouDataSource: [],
    HaHaDouPageNo: 1,
    HaHaDouTotal: 5,
    realMemberName: '',//是否实名认证
    authenticationName: '', //实名认证姓名
    hrefMode: null
  };
  async componentDidMount() {
    const urlParams = new URLSearchParams(this.props.location.search);
    const hrefMode = urlParams.get('mode');
    this.setState({
      hrefMode
    })
    await this.getBasicData()
    await this.getDynamicData()
    await this.getBannedData()
    await this.getScoreData()
    await this.getCouponData()
    await this.getIntegralRecord()
    await this.getRiskBannedData()
  }
  getCouponData = async () => {
    const { memberId } = this.props.match.params
    const { couponPageNo } = this.state
    let res = await apimemberDetailCouponPage({ memberId, pageNo: couponPageNo, pageSize: 5 })
    if (res.code === 0 && res.data) {
      this.setState({ couponData: res.data, couponPageNo: res.pageNo, couponTotal: res.totalCount })
    }
  }
  getBannedData = async () => {
    const { memberId } = this.props.match.params
    const { bannedPageNo } = this.state
    let res = await apiMemberBannedRecordPage({ pageNo: bannedPageNo, pageSize: 5, memberId })
    if (res.code === 0 && res.data) {
      console.log(res.data);
      this.setState({ bannedData: res.data, bannedPageNo: res.pageNo, bannedTotal: res.totalCount })
    }
  }
  getRiskBannedData = async () => {
    const { memberId } = this.props.match.params
    const { riskBannedPageNo } = this.state
    let res = await apiMemberBlockingAndUnblockingRecordQueryHistoryBanned({ memberId })
    if (res.code === 0 && res.data) {
      this.setState({
        riskBannedData: res.data,
        riskBannedPageNo: res.pageNo,
        riskBannedTotal: res.totalCount
      })
    }
  }
  goView = (id) => {
    this.props.history.push(`/riskControl/report/view/${id}`)
  }
  getDynamicData = async () => {
    const { memberId } = this.props.match.params
    const { dynamicPageNo } = this.state
    let res = await apiMemberDynamicPage({ memberId, pageNo: dynamicPageNo, pageSize: 5 })
    if (res.code === 0 && res.data) {
      this.setState({ dynamicData: res.data, dynamicPageNo: res.pageNo, dynamicTotal: res.totalCount })
    }
  }

  getBasicData = async () => {
    const { memberId } = this.props.match.params
    let response = await apiGetUserDetails({ memberId })
    let typeLabel = ''
    let statusLabel = ''
    switch (response.data.memberType) {
      case 'R':
        typeLabel = '注册会员'
        break;
      case "P":
        typeLabel = '正式会员'
        break;
      case "S":
        typeLabel = "商户会员"
        break;
      default:
        typeLabel = "返回值错误"
    }
    switch (response.data.memberStatus) {
      case 'Y':
        statusLabel = `正常`
        break
      case 'N':
        statusLabel = `冻结 (${response.data.freezeTime})`
        break
      default:
        statusLabel = '返回值错误'
    }
    if (response.code === 0 && response.data) {
      var reg = /^(\d{3})\d{4}(\d{4})$/;
      var memberMobile = response.data.memberMobile.toString().replace(reg, '$1****$2');
      let basicData = [
        {
          title: "手机号",
          value:maskNumber(memberMobile.toString(),3,4) ,
        },
        {
          title: "身份",
          value: typeLabel
        },
        {
          title: "用户状态",
          value: statusLabel
        },
        {
          title: "注册时间",
          value: response.data.memberCreatedTime,
        },
        {
          title: "关注",
          value: parseInt(response.data.focusNum || 0).toLocaleString(),
        },
        {
          title: "粉丝",
          value: parseInt(response.data.fansNum || 0).toLocaleString(),
        },
        {
          title: "冻结原因",
          value: response.data.freezeReason || '未封禁',
        },
        {
          title: "个性签名",
          value: response.data.individualitySignature || '',
        },
        {
          title: "积分",
          value: parseInt(response.data.scoreBalance || 0).toLocaleString(),
        },
        {
          title: "会员等级",
          value: <div>
            <TheImage src={response.data.levelImg} width={18} height={18} preview={false} />
            <span style={{ marginLeft: 5 }}>{response.data.memberLevel}</span>
          </div>,
        },
        {
          title: "哈哈豆",
          value: response.data.integralTotal || 0,
        },
        // {
        //   title: "钱包余额",
        //   value: <div>
        //     <TheButton onClick={()=> this.props.history.push(`/wallet/userBalance/detail/${memberId}`)}>{(response.data.memberWalletPrice / 100).toFixed(2) || 0.00}</TheButton>
        //   </div>
        // },
        {
          title: "宠币",
          value: <div>
            <TheButton onClick={() => this.props.history.push(`/myPocket/coinsAccount/detail/${memberId}`)}>{response.data.coinBalance || 0}</TheButton>
          </div>
        },
        {
          title: "礼物收益",
          value: <div>
            <TheButton onClick={() => this.props.history.push(`/myPocket/userBalance/detail/${memberId}`)}>{(response.data.currentIncome / 100).toFixed(2) || 0.00}</TheButton>
          </div>
        },
        {
          title: "最近一次活跃时间",
          value: response.data.lastActiveTime || '',
        },
        {
          title: "注销时间",
          value: response.data.deletedTime || '',
        },
      ]
      let nickName = response.data.nickName
      let memberSex = response.data.memberSex
      let realMemberName = response.data.realMemberName
      this.setState({
        basicData, nickName, memberSex, realMemberName,
      })
    }
  }
  openDialog = (dynamicId) => {
    this.setState({ visible: true, dynamicId });
  };
  closeDialog = () => {
    this.setState({ visible: false });
  };
  pageCouponChange = pageNo => {
    this.setState({
      couponPageNo: pageNo
    }, () => { this.getCouponData() })
  }
  pageChange = (pageNo) => {
    this.setState({
      dynamicPageNo: pageNo
    }, () => {
      this.getDynamicData()
    })
  }
  pageBannedChange = pageNo => {
    this.setState({
      bannedPageNo: pageNo
    }, () => { this.getBannedData() })
  }
  pageRiskBannedChange = pageNo => {
    this.setState({
      riskBannedPageNo: pageNo
    }, () => { this.getBannedData() })
  }
  pageScoreChange = pageNo => {
    this.setState({
      scorePageNo: pageNo
    }, () => {
      this.getScoreData()
    })
  }
  pageHaHaDouChange = pageNo => {
    this.setState({
      HaHaDouPageNo: pageNo
    }, () => {
      this.getIntegralRecord()
    })
  }

  getScoreData = async () => {
    const { memberId } = this.props.match.params
    const { scorePageNo } = this.state
    let res = await apiGetScorePage({ memberId, pageNo: scorePageNo, pageSize: 5 })
    if (res.data && res.code === 0) {
      this.setState({
        scorePageNo: res.pageNo,
        scoreDataSource: res.data,
        scoreTotal: res.totalCount
      })
    }
  }
  getIntegralRecord = async () => {
    const { memberId } = this.props.match.params
    const { HaHaDouPageNo } = this.state
    let res = await apiMemberIntegralRecord({ memberId, current: HaHaDouPageNo, size: 5 })
    if (res.data && res.code === 0) {
      this.setState({
        HaHaDouDataSource: res.data.records,
        HaHaDouPageNo: res.data.current,
        HaHaDouTotal: res.data.total
      })
    }
  }
  GoBack() {
    this.props.history.replace(`/users`)
  }
  render() {
    const {
      memberSex,
      nickName,
      basicData,
      couponColumns,
      dynamicColumns,
      bannedColumns,
      couponData,
      dynamicData,
      bannedData,
      couponPageNo,
      dynamicPageNo,
      bannedPageNo,
      couponTotal,
      dynamicTotal,
      bannedTotal,
      visible,
      dynamicId,
      scoreColumns,
      scoreDataSource,
      scorePageNo,
      scoreTotal,
      HaHaDouColumns,
      HaHaDouDataSource,
      HaHaDouPageNo,
      HaHaDouTotal,
      realMemberName,
      riskBannedColumns,
      riskBannedData,
      riskBannedPageNo,
      riskBannedTotal,
      hrefMode
    } = this.state;
    return (
      <div className="p-layout-box users-details">
        <GoBack history={hrefMode ? () => this.GoBack() : this.props.history} title="会员详情" />
        <div className="p-layout-box">
          <div className="users-basic">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div className="title">
                <span>{nickName}</span>
                {
                  memberSex === 1 && <ManOutlined style={{ color: "#74B9EB" }} />
                }
                {
                  memberSex === 2 && <WomanOutlined style={{ color: "#CE4F97" }} />
                }
              </div>
              <span style={{ fontSize: 13 }}>{realMemberName} </span>
            </div>

            <div className="basic-content">
              {basicData.map((v, i) => {
                return (
                  <div key={i}>
                    <span>{v.title}:</span>
                    <span>{v.value}</span>
                  </div>
                );
              })}
            </div>
          </div>
          <div className="divider-line"></div>
          <div className="details-list">
            <div className="list-content">
              <div className="list-content">
                <div className="title">优惠券</div>
                <TheTable columns={couponColumns} dataSource={couponData} />
                <div className="pagination-box">
                  <Pagination
                    current={couponPageNo}
                    pageSize={5}
                    onChange={this.pageCouponChange}
                    hideOnSinglePage
                    total={couponTotal}
                  />
                </div>
              </div>
              <div className="title">用户动态</div>
              <TheTable columns={dynamicColumns} dataSource={dynamicData} />
              <div className="pagination-box">
                <Pagination
                  current={dynamicPageNo}
                  pageSize={5}
                  onChange={this.pageChange}
                  hideOnSinglePage
                  total={dynamicTotal}
                />
              </div>
            </div>
            <div className="list-content">
              <div className="title">封禁记录</div>
              <TheTable columns={bannedColumns} dataSource={bannedData} />
              <div className="pagination-box">
                <Pagination
                  current={bannedPageNo}
                  pageSize={5}
                  onChange={this.pageBannedChange}
                  hideOnSinglePage
                  total={bannedTotal}
                />
              </div>
              <Table
                columns={riskBannedColumns}
                dataSource={riskBannedData}
                pagination={{
                  position: ['bottomCenter'],
                }}
                rowKey={(record) => record.reportingRecordsId}
              />
            </div>
            <div className="list-content">
              <div className="title">积分记录</div>
              <TheTable columns={scoreColumns} dataSource={scoreDataSource} />
              <div className="pagination-box">
                <Pagination
                  current={scorePageNo}
                  pageSize={5}
                  onChange={this.pageScoreChange}
                  hideOnSinglePage
                  total={scoreTotal}
                />
              </div>
            </div>
            <div className="list-content">
              <div className="title">哈哈豆记录</div>
              <TheTable columns={HaHaDouColumns} dataSource={HaHaDouDataSource} />
              <div className="pagination-box">
                <Pagination
                  current={HaHaDouPageNo}
                  pageSize={5}
                  onChange={this.pageHaHaDouChange}
                  hideOnSinglePage
                  total={HaHaDouTotal}
                />
              </div>
            </div>
          </div>
        </div>
        <TheDialog
          title="动态详情"
          visible={visible}
          width={260}
          footer={null}
          handleCancel={this.closeDialog}
        >
          <DynamicDetails nickName={nickName} dynamicId={dynamicId} closeDialog={this.closeDialog} />
        </TheDialog>
      </div>
    );
  }
}

export default Details;
